<template>
  <div class="chat-layout">
    <el-row class="main-row">
      <!-- 左侧：在线用户 -->
      <el-col :xs="24" :sm="24" :md="6" :lg="6">
        <el-card class="online-users">
          <h3 slot="header" class="header">在线用户</h3>
          <el-scrollbar>
            <div v-for="user in onlineUsers" :key="user.id" class="user-item">
              <div class="avatar-blog-image2">
                <img :src="user.avatar" alt="User Avatar" class="avatar-image">
              </div>
              <span class="user-name">{{ user.name }}</span>
            </div>
          </el-scrollbar>
        </el-card>
      </el-col>

      <!-- 右侧：聊天框和发送消息 -->
      <el-col :xs="24" :sm="24" :md="18" :lg="18" border>
        <div class="chat-wrapper" ref="chatWrapper">
          <el-card class="chat-room">
            <el-scrollbar ref="messageContainer" @scroll="handleScroll" >
              <div class="load-more" v-if="hasMoreMessages" @click="loadMoreMessages">加载更多</div>

              <div
                v-for="message in displayedMessages"
                :key="message.id"
                class="message-item"
                :class="{ 'my-message': message.isMyMessage }"
              >

                <div class="avatar-blog-image">
                  <img :src="message.avatar" alt="User Avatar" class="avatar-image">
                </div>
                <div class="message-content">
                  <p class="message-time">{{ message.date }}</p> <!-- 添加这一行 -->
                  <p class="sender">{{ message.name }}</p>
                  <p class="text">{{ message.text }}</p>

                </div>
              </div>
            </el-scrollbar>
          </el-card>

          <!-- 发送消息输入框和按钮在同一行，无垂直间距 -->
          <el-row class="message-input-row">
            <el-col :span="18" class="message-input-col">
              <el-input v-model="newMessage" placeholder="请输入消息..." class="message-input"></el-input>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="sendMessage" class="send-button">发送</el-button>
            </el-col>
          </el-row>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
    import {getToken} from "../utils/auth";
    import {getMoreMessage, getNew10ChattingRecords, getOnlineUserInfo} from "../api/chat";
    import { mapMutations } from 'vuex';


    export default {
        data() {
            return {
                chatUserInfo:null,
                url: "ws://154.8.200.181:8989/websocket/message/" + getToken(),
                message: "",
                text_content: "",
                ws: null,

                onlineUsers: [

                ],
                messages: [

                ],
                newMessage: '',
                currentPage: 1,
                pageSize: 8,
                tempPageSize:8,
                loadingMore: false,
            };
        },
        computed: {
            displayedMessages() {
                const startIndex = Math.max(this.messages.length - this.pageSize, 0);
                return this.messages.slice(startIndex);
            },
            hasMoreMessages() {
               return true;
            },
        },
        methods: {
          ...mapMutations(['setNewMessageStatus']),
            getChatInfo(){
                getNew10ChattingRecords().then((resp=>{
                  this.messages = resp.data
                }))

            },
            getOnlineUserInfo(){
                getOnlineUserInfo().then((resp=>{
                    this.chatUserInfo = resp.data
                }))
            },

            startHeartbeat() {
                // 每隔一定时间（例如30秒），发送心跳消息
                this.heartbeatInterval = setInterval(() => {
                    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
                        this.ws.send("ping");
                    }
                }, 30000); // 30秒
            },

            stopHeartbeat() {
                // 停止心跳定时器
                clearInterval(this.heartbeatInterval);
            },

            join() {
                const wsuri = this.url;
                this.ws = new WebSocket(wsuri);
                const self = this;
                this.ws.onopen = function (event) {
                    self.$message('连接成功！');
                    // 在连接成功时开始心跳
                    self.startHeartbeat();
                };
                this.ws.onmessage = function (event) {
                    if ("pong" == event.data){
                        console.log("pong")
                        return;
                    }
                    if ("noAuth" == event.data){
                        self.$router.push({path:'/Login'});
                        return;
                    }
                    const result = JSON.parse(event.data);
                    // 在线用户
                    if (result.type == 1) {
                        self.onlineUsers = result.data;
                    } else if (result.type == 2) {
                        // 发送消息
                        const parse = JSON.parse(result.data);
                        const newMessageObj = {
                            id: self.messages.length + 1,
                            name: parse.name,
                            avatar: parse.avatar,
                            text: parse.text,
                            isMyMessage: parse.id == self.chatUserInfo.id,
                            date: parse.date
                        };
                        self.messages.push(newMessageObj);
                        // 在其他组件中
                        self.setNewMessageStatus(true);

                    }
                };
                this.ws.onclose = function (event) {
                    self.text_content = self.text_content + "已经关闭连接!" + "\n";
                    // 在连接关闭时停止心跳
                    self.stopHeartbeat();
                    self.$message('聊天室已经退出！');
                };
            },
            exit() {
                if (this.ws) {
                    this.ws.close();
                    this.ws = null;
                }
            },
            send() {
                if (this.ws) {
                    this.ws.send(this.message);
                } else {
                    alert("未连接到服务器");
                }
            },

            loadMoreMessages() {
                this.loadingMore = true;
                getMoreMessage(this.currentPage,this.tempPageSize).then(resp=>{
                  if (resp.data.num == 0){
                      this.$message('已经没有消息了！！');
                      return;
                  }
                  this.pageSize = this.pageSize + 8
                  this.currentPage = this.currentPage + 1
                    for (let i = 0; i < resp.data.rows.length; i++) {
                        this.messages.unshift(resp.data.rows[i])
                    }
                })

            },
             formatDate(date) {
              const year = date.getFullYear();
              const month = (date.getMonth() + 1).toString().padStart(2, '0');
              const day = date.getDate().toString().padStart(2, '0');
              const hours = date.getHours().toString().padStart(2, '0');
              const minutes = date.getMinutes().toString().padStart(2, '0');
              const seconds = date.getSeconds().toString().padStart(2, '0');
              return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            },

            sendMessage() {
                if (!this.ws || this.ws.readyState === WebSocket.CLOSED) {
                    // 如果 WebSocket 不存在或已关闭，重新创建连接
                    this.join();
                }
                const formattedDate = this.formatDate(new Date())
                if (this.newMessage.trim() !== '') {
                    const newMessageObj = {
                        id: this.chatUserInfo.id,
                        name: this.chatUserInfo.name,
                        avatar: this.chatUserInfo.avatar,
                        text: this.newMessage,
                        isMyMessage: true,
                        date: formattedDate
                    };
                    this.ws.send(JSON.stringify(newMessageObj));
                    this.newMessage = '';
                }
            },
            handleScroll() {
                // 如果滚动到顶部并且有更多消息，触发加载更多
                if (
                    this.$refs.messageContainer.$el.scrollTop === 0 &&
                    this.hasMoreMessages &&
                    !this.loadingMore
                ) {
                    this.loadMoreMessages();
                }
            },

        },
        beforeDestroy() {
            this.stopHeartbeat();
        },

        created() {
          this.join()
          this.getOnlineUserInfo();
          this.getChatInfo()
        }
    };
</script>

<style scoped>
  .chat-room {
    flex: 1;
    overflow-y: auto;
  }

  .chat-room::-webkit-scrollbar {
    width: 0;  /* Remove scrollbar space */
    background: transparent;  /* Optional: just make scrollbar invisible */
  }

  .avatar-blog-image2 {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 15%;
    height: 40px;
    border-radius: 50%;
    overflow: hidden;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
    transition: transform 0.3s ease-in-out;
  }
  .avatar-image {
    width: 100%;
    height: auto;
  }
  .avatar-blog-image {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 5%;
    height: 40px;
    border-radius: 50%;
    overflow: hidden;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
    transition: transform 0.3s ease-in-out;
  }
  .chat-wrapper {
    width: 100%;
    height: 500px;
    position: relative;

    display: flex;
    flex-direction: column;
  }

  .chat-room {
    flex: 1;
    overflow-y: auto;

  }

  .message-item {
    display: flex;
    align-items: center;
    margin: 10px 0;
    padding: 10px;
    border-radius: 8px;
  }

  .message-item.my-message {
    justify-content: flex-end;
  }

  .message-item .message-content {
    margin-left: 10px;
  }

  .sender {
    font-weight: bold;
  }

  .text {
    margin-top: 5px;
    word-break: break-all;
  }

  .message-input-row {
    margin-top: 10px;
  }

  .message-input-col {
    margin-right: 0;
  }

  .message-input {
    width: 100%;
  }

  .send-button {
    width: 100%;
  }

  .load-more {
    text-align: center;
    cursor: pointer;
    color: #409eff;
  }

  /* 以下是原来的样式，复制过来保持一致性 */
  .chat-layout {
    padding: 20px;
  }
  .header {
    background-color: #409EFF;
    padding: 10px;
    text-align: center;
    color: #fff;
  }

  .online-users {
    margin-bottom: 20px;
    height: 500px;
  }

  .user-item {
    display: flex;
    align-items: center;
    margin: 10px 0;
  }

  .user-name {
    margin-left: 10px;
  }

  .chat-room {
    width: 100%;
    height: 433px;
  }

  .message-item {
    display: flex;
    align-items: center;
    margin: 10px 0;
    padding: 10px;
    border-radius: 8px;
  }

  .message-item.my-message {
    justify-content: flex-end;
  }

  .message-item .message-content {
    margin-left: 10px;
  }

  .sender {
    font-weight: bold;
  }

  .text {
    max-width: 280px;
    word-break: break-all;
  }

  .message-input-row {

  }

  .message-input-col {
    margin-right: 0; /* 移除列之间的右边距 */
  }

  .message-input {
    width: 100%;
  }

  .send-button {
    width: 100%;
  }
</style>
